package com.lw.leetcode.add.a;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * a
 * arr
 * https://leetcode.cn/contest/autox2023/problems/8p6t8R/
 * AutoX-2. 蚂蚁王国的蜂蜜
 *
 * @author liw
 * @version 1.0
 * @date 2023/2/10 17:44
 */
public class HoneyQuotes {

    public double[] honeyQuotes(int[][] handle) {
        double sum = 0;
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        List<Double> list = new ArrayList<>();
        for (int[] ints : handle) {
            int t = ints[0];
            if (t == 1) {
                map.merge(ints[1], 1, (a, b) -> a + b);
                sum += ints[1];
                count++;
            } else if (t == 2) {
                int c = map.get(ints[1]);
                if (c == 1) {
                    map.remove(ints[1]);
                } else {
                    map.put(ints[1], c - 1);
                }
                sum -= ints[1];
                count--;
            } else if (t == 3) {
                if (count == 0) {
                    list.add(-1D);
                } else {
                    list.add(sum / count);
                }
            } else {
                if (count == 0) {
                    list.add(-1D);
                    continue;
                }
                double v = sum / count;
                double f = 0;
                for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                    f += Math.pow(entry.getKey() - v, 2) * entry.getValue();
                }
                list.add(f / count);
            }
        }
        int size = list.size();
        double[] values = new double[size];
        for (int i = 0; i < size; i++) {
            values[i] = list.get(i);
        }
        return values;
    }

}
